﻿using System.Security.Cryptography;
using System.Text;

namespace StationDataHub.Common;

public static class EncryptUtils
{
    /// <summary>
    /// AES CBC PKCS7 加密
    /// </summary>
    public static string EncryptAES(this string plainText, string key, string iv)
    {
        using var aes = Aes.Create();
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = Encoding.UTF8.GetBytes(iv);
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
        var bytes = Encoding.UTF8.GetBytes(plainText);
        var encrypted = encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        return Convert.ToBase64String(encrypted);
    }

    /// <summary>
    /// AES CBC PKCS7 解密
    /// </summary>
    public static string DecryptAES(this string cipherText, string key, string iv)
    {
        using var aes = Aes.Create();
        aes.Key = Encoding.UTF8.GetBytes(key);
        aes.IV = Encoding.UTF8.GetBytes(iv);
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.PKCS7;

        using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
        var bytes = Convert.FromBase64String(cipherText);
        var decrypted = decryptor.TransformFinalBlock(bytes, 0, bytes.Length);
        return Encoding.UTF8.GetString(decrypted);
    }

    /// <summary>
    /// HMAC-MD5 签名（大写）
    /// </summary>
    public static string GetHmacMd5(this string text, string key)
    {
        var keyBytes = Encoding.UTF8.GetBytes(key);
        var textBytes = Encoding.UTF8.GetBytes(text);
        using var hmac = new HMACMD5(keyBytes);
        var hashBytes = hmac.ComputeHash(textBytes);
        return Convert.ToHexString(hashBytes).ToUpper();
    }
}
